package com.zanfeng.signleplatform.provider.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zanfeng.signleplatform.api.exception.AppRuntimeException;
import com.zanfeng.signleplatform.common.auth.ApiTokenResult;
import com.zanfeng.signleplatform.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class TokenUtil {

    private final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    private JWTVerifier verifier;

    private static String kTokenKey = "signleplatform";

    public ApiTokenResult createToken(String userId) {
        return createToken(Constants.kPrefix_Module, userId);
    }

    public ApiTokenResult checkToken(String token) {
        return checkToken(Constants.kPrefix_Module, token);
    }

    public ApiTokenResult createToken(String prefix, String userId) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(Constants.kToken_Secret);
            String token = JWT.create().withClaim("uid", userId).sign(algorithm);
            return new ApiTokenResult(userId, token);
        } catch (Exception exception) {
            throw new AppRuntimeException("token生成失败");
        }
    }

    public ApiTokenResult checkToken(String prefix, String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        DecodedJWT jwt = null;
        try {
            if (verifier == null) {
                Algorithm algorithm = Algorithm.HMAC256(Constants.kToken_Secret);
                verifier = JWT.require(algorithm).build(); //Reusable verifier instance
            }
            jwt = verifier.verify(token);
            return new ApiTokenResult(jwt.getClaims().get("uid").asString());
        } catch (Exception e) {
            logger.error("checkToken error : {}", e.getLocalizedMessage());
            return null;
        }
    }

}
